package fi.foyt.cs.api.items;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.ext.oauth.protectedresource.ScopedResource;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;

import fi.foyt.cs.Scope;
import fi.foyt.cs.api.APIResource;
import fi.foyt.cs.api.json.EntityRendererVault;
import fi.foyt.cs.controller.ItemController;
import fi.foyt.cs.controller.SceneController;
import fi.foyt.cs.controller.UserController;
import fi.foyt.cs.persistence.domainmodel.items.StashedItem;
import fi.foyt.cs.persistence.domainmodel.scene.Scene;
import fi.foyt.cs.persistence.domainmodel.user.User;

public class ListStashedItemsResource extends APIResource implements ScopedResource {

  @Get ("json")
  @Post ("json")
  public Representation represent() throws ResourceException {
    JSONObject result = new JSONObject();
    
    Long sceneId = getLongAttribute("sceneId");

    UserController userController = new UserController();
    ItemController itemController = new ItemController();
    SceneController sceneController = new SceneController();

    try {
      User user = userController.findUserByIdentifier(getClientInfo().getUser().getIdentifier());
      if (user != null) {
        List<StashedItem> stashedItems;
        if (sceneId == null) {
          stashedItems = itemController.listStashedItemsByUser(user);
        } else {
          Scene scene = sceneController.findSceneById(sceneId);
          stashedItems = itemController.listStashedItemsByUserAndScene(user, scene);
        }
          
        JSONArray itemsJson = new JSONArray();

        for (StashedItem stashedItem : stashedItems) {
          itemsJson.put(EntityRendererVault.getInstance().renderEntity(getLocale(), stashedItem));
        }

        result.put("stashedItems", itemsJson);

      } else {
        throw new ResourceException(Status.CLIENT_ERROR_UNAUTHORIZED, "User not found");
      }
    } catch (JSONException e) {
      throw new ResourceException(e);
    }

    return new JsonRepresentation(result);
  }

  public String getOwner(Reference uri) {
    return null;
  }

  public String[] getScope(Reference uri) {
    return new String[] { Scope.StashedItems.getIntenal() };
  }
}
